package com.web.cloud.shiro;

import com.web.cloud.model.sm.SmUser;
import com.web.cloud.service.sm.SmUserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户身份验证,授权 Realm 组件
 * 
 * @author liuhaiming
 * @since 2015-12-20
 **/
@Component(value = "shiroRealm")
public class ShiroRealm extends AuthorizingRealm {
    private Logger log = Logger.getLogger(ShiroRealm.class);

    @Resource
    private SmUserService userService;

    @Autowired
    private HttpSession session;

    /**
     * 设定Password校验.
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        //该句作用是重写shiro的密码验证，让shiro用我自己的验证
        setCredentialsMatcher(new CredentialsMatcher());
    }

    /**
     * 权限检查
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        log.info("authorization info" + shiroUser.getSmUser().getCode());

        return authorizationInfo;
    }

    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = String.valueOf(token.getPrincipal());

        // 通过数据库进行验证
        final SmUser authUser = userService.selectByLoginName(username);

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(new ShiroUser(authUser), authUser.getPassword(), getName());
        return authenticationInfo;
    }

}
